from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_login import LoginManager
from config import DevelopmentConfig

db = SQLAlchemy()


def create_app():
    app = Flask(__name__)
    app.config.from_object(DevelopmentConfig)

    CORS(app, supports_credentials=True, origins='http://localhost:8080')
    db.init_app(app)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'api.login'

    from app.api.views import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')

    from db.models import User  # 确保 User 类是正确的

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    return app
